package mware_lib;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class ProxyCache<T> {
  Class<T> cls;
  Map<ObjectRef, T> cache = new HashMap<>();

  public ProxyCache(Class<T> cls) {
    this.cls = cls;
  }
  
  public T returnCached(Object Ref) {
    if (Ref == null)
      throw new RuntimeException("Unbekannte Objektreferenz");
    ObjectRef oRef = (ObjectRef) Ref;
    if (!cache.containsKey(oRef)) {
      try {
        cache.put(oRef, cls.getConstructor(ObjectRef.class).newInstance(oRef));
      } catch(NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException("Proxyobjekt " + cls + " konnte nicht initialisiert werden (" + e + ")");
      }
    }
    return cache.get(oRef);
  }
}
